<template>
	<i-addressPicker v-model="showPicker" @confirm="confirm"></i-addressPicker>
	<i-picker :value="valueData" @confirm="pickerChange" :list="[selectData]" v-model="showBusinessPicker"></i-picker>
	<view class="store_apply">
		<view class="banner">
			<image src="https://tyj-apk-1258993110.cos.ap-nanjing.myqcloud.com/images/sjsq_banner.jpg" mode=""></image>
		</view>
		<view class="store_state" v-if="merchantEntryStatus">
			<view class="state_left">
				<image v-if="merchantEntryStatus === '1'" src="../../static/images/fail_icon.png" mode=""></image>
				<image v-if="merchantEntryStatus === '0'" src="../../static/images/wait_icon.png" mode=""></image>
			</view>
			<view class="state_right">
				<text class="status">{{merchantEntryStatus === '1' ? '已驳回' : '审核中'}} </text>
				<text class="entryRemark">{{merchantEntryStatus === '1' ? entryRemark : '请等待平台审核'}}</text>
			</view>
		</view>
		<view style="margin-top: 48rpx;">
			<i-tab :active="tabList.findIndex(i=>i.id === formData.merType)" :list="tabList" type="switch" @change="tabJoin"></i-tab>
		</view>
		<view class="form">
			<i-formItem title="商家名称">
				<input :disabled="disabled" v-model="formData.merName" type="text" placeholder="请输入商家名称">
			</i-formItem>
			<i-formItem v-if="formData.merType === '1'" title="业务类型" :require="true">
				<view class="selectMap" @click="showpick">
					<text v-if="businessStr" :style="{color: disabled ? '#A0A0A0' : '#16161F'}">{{businessStr}}</text>
					<text v-else>请选择业务类型</text>
					<image src="../../static/images/goto_icon.png" mode=""></image>
				</view>
			</i-formItem>
			<i-formItem title="所在城市">
				<view class="selectMap" @click="showSelect">
					<text v-if="addressName" :style="{color: disabled ? '#A0A0A0' : '#16161F'}">{{addressName}}</text>
					<text v-else>请选择省市区县</text>
					<image src="../../static/images/goto_icon.png" mode=""></image>
				</view>
			</i-formItem>
			<view class="select_location" @click="selectMap">
				<view class="but">选择商家位置</view>
			</view>
			<i-formItem title="详细地址">
				<input :disabled="disabled" maxlength="50" v-model="formData.address" type="text"
					placeholder="精确到街道门牌号，长度3-50位">
			</i-formItem>
			<i-formItem title="手机号">
				<input :disabled="disabled" v-model="formData.mobile" type="number" placeholder="请输入门店电话">
			</i-formItem>
			<i-formItem title="门店LOGO" align="top">
				<i-upLoad :disabled="disabled" v-model="formData.doorPhotoUrl"></i-upLoad>
			</i-formItem>
			<i-formItem title="门店图片（可上传多张）" align="top">
				<view class="imagelist" style="padding-bottom: 24rpx;">
					<view class="" v-for="(item, index) in formData.imageList" :key="index">
						<i-upLoad :disabled="disabled" right="20rpx" v-model="formData.imageList[index]"
							@success="successList" @remove="removeList(index)">
						</i-upLoad>
					</view>
				</view>
			</i-formItem>
		</view>
		<view class="lines"></view>
		<view class="buttons" v-if="!disabled">
			<view class="agreement">
				<radio @click="checkValue = !checkValue" :checked="checkValue" color="#FB652E"
					style="transform:scale(0.7)" />
				<text>我已阅读并同意</text>
				<text style="color: #FB652E;"
					@click="navTo('/pages/views/accord?agreementId=10010014', 'navigateTo')">《商家入驻协议》</text>
			</view>
			<i-buttons v-if="!merchantEntryStatus" radius="4" padding="18rpx 0" size="32" color="#fff" bgColor="#FB652E"
				@click="submit">立即申请
			</i-buttons>
			<i-buttons v-else-if="merchantEntryStatus === '1'" radius="4" padding="18rpx 0" size="32" color="#fff"
				bgColor="#FB652E" @click="updateClick">重新提交
			</i-buttons>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import {
		reactive,
		ref,
		computed
	} from 'vue'
	import {
		onLoad,
		onReady
	} from '@dcloudio/uni-app'
	import {
		showTost,
		checkForm,
		navTo,
		getAppQX
	} from '../../utils/common'
	import {
		nameReg,
		bankReg,
		phoneReg,
		addressReg
	} from '../../utils/regs'
	import useStore from '../../stores/index'
	import {
		appleMerchant,
		getAppleMerchant,
		updateAppleMerchant,
		getLocalMeBusinessTypes
	} from '../../api/store'
	import {
		getAd
	} from '../../api/index'
	const store = useStore()
	const formData = reactive<any>({
		"address": "",
		"cityCode": "",
		"countryCode": "",
		"doorPhotoUrl": "",
		"imageList": [''],
		"latitude": "",
		"longitude": "",
		"merName": "",
		"mobile": "",
		"proviceCode": "",
		"storeName": "",
		"merType":'0',
		"businessType":""
	})
	const entryRemark = ref('')
	const showPicker = ref(false)
	const disabled = ref(false)
	const addressName = ref('')
	const merchantEntryStatus = ref<string | null>('')
	const checkValue = ref(false)
	const businessStr = ref('')
	const showBusinessPicker = ref(false)
	const selectData = ref([])
	const valueData = ref<any>([])

	const rules = {
		mobile: {
			reg: phoneReg,
			message: '请输入正确手机号'
		},
		address: {
			reg: addressReg,
			message: '详细地址长度在3-50位'
		},

	}
	
	const tabList = ref([
		{ title: '汽服门店', id: '0' },
		{ title: '生活门店', id: '1' },
	])
	
	const tabJoin = (e : { id : number }) => {
		formData.merType = e.id
	}

	onLoad((option) => {
		if (option.merchantEntryStatus === '0') {
			getPageData()
			disabled.value = true
		} else if (option.merchantEntryStatus === '1') {
			getPageData()
		}else{
			getBusinessData()
		}
		merchantEntryStatus.value = option.merchantEntryStatus
	})

	const getPageData = async () => {
		const {
			data
		} = await getAppleMerchant()

		for (let key in formData) {
			if (formData.hasOwnProperty(key)) {
				formData[key] = data[key]
			}
		}
		formData.merId = data.merId
		formData.storeId = data.storeId
		formData.businessType = data.businessType
		businessStr.value = formData.businessType
		!disabled.value && formData.imageList.push('')
		entryRemark.value = data.entryRemark
		addressName.value = (data?.provinceName || "") + (data?.cityName || "") + (data?.countyName || "")

		getBusinessData()
	}

	const showSelect = () => {
		if (disabled.value) {
			return
		}
		showPicker.value = true
	}

	const selectMap = () => {
		if (disabled.value) {
			return
		}
		if (getAppQX('locationAuthorized')) {
			uni.chooseLocation({
				success: (res) => {
					formData.latitude = res.latitude + ''
					formData.longitude = res.longitude + ''
					formData.address = res.address
				},
				fail: (err) => {
					console.log(err, 'errerr');
				}
			});
		}
	}
	const confirm = (data : any) => {
		addressName.value = data.address
		formData.cityCode = data.city
		formData.proviceCode = data.province
		formData.countryCode = data.county
	}
	const submit = async () => {
		if (!checkValue.value) {
			showTost('请勾选商家入驻协议')
			return
		}
		formData.storeName = formData.merName
		const unCheck = formData.merType === '1'?['licensePic','cityCode', 'countryCode', 'merRealName', 'bankNo', 'bankName', 'corporatePic', 'entryRemark']:['licensePic','cityCode', 'countryCode', 'merRealName', 'bankNo', 'bankName', 'corporatePic', 'entryRemark','businessType']
		const check = checkForm(formData, unCheck, rules)
		if (check) {
			return
		}

		const list = formData.imageList.filter((item : string) => item)
		if (!list.length) {
			showTost('请上传门店图片')
			return
		}
		formData.imageList = list

		await appleMerchant(formData)
		store.setUserInfo()
		showTost('商户申请成功', () => {
			navTo('', 'navigateBack')
		})
	}

	const updateClick = async () => {
		if (!checkValue.value) {
			showTost('请勾选商家入驻协议')
			return
		}
		formData.storeName = formData.merName
		const unCheck = formData.merType === '1'?['licensePic','cityCode', 'countryCode', 'merRealName', 'bankNo', 'bankName', 'corporatePic', 'entryRemark']:['licensePic','cityCode', 'countryCode', 'merRealName', 'bankNo', 'bankName', 'corporatePic', 'entryRemark','businessType']
		const check = checkForm(formData, unCheck, rules)
		if (check) {
			console.log(check, 'check');
			return
		}

		const list = formData.imageList.filter((item : string) => item)
		if (!list.length) {
			showTost('请上传门店图片')
			return
		}
		formData.imageList = list
		await updateAppleMerchant(formData)
		store.setUserInfo()
		showTost('提交申请成功', () => {
			navTo('', 'navigateBack')
		})
	}

	const successList = () => {
		if (formData.imageList.length < 9 && !(formData.imageList.some((item : string) => !item)))
			formData.imageList.push('')
	}
	const removeList = (index : number) => {
		if (formData.imageList.length > 1) {
			formData.imageList.splice(index, 1)
		}
	}

	const showpick = () => {
		if (disabled.value) {
			return
		}
		showBusinessPicker.value = true
	}

	const getBusinessData = async () => {
		const { data } = await getLocalMeBusinessTypes()
		selectData.value = data.map((item : { businessType : string, businessTypeLabel : string }) => {
			return {
				label: item.businessTypeLabel,
				value: item.businessType
			}
		})
		selectData.value.unshift({label: '',value: ''})
		if(formData.businessType!=""){
			valueData.value = selectData.value.filter(item => item.value === formData.businessType)
			businessStr.value = valueData.value[0].label
		}
	}

	const pickerChange = (data : any) => {
		valueData.value = data
		formData.businessType = data[0].value
		businessStr.value = data[0].label
	}

</script>

<style lang="scss" scoped>
	.store_apply {
		width: 100%;

		.banner {
			width: calc(100% - 64rpx);
			height: 200rpx;
			margin: 20rpx auto;

			image {
				width: 100%;
				height: 100%;
				border-radius: 16rpx;
			}
		}

		.form {
			width: calc(100% - 64rpx);
			margin: 0 auto;
			margin-top: 20rpx;
			@include dfont;

			input {
				width: 72%;
			}

			image {
				width: 12rpx;
				height: 18rpx;
			}

			.selectMap {
				width: 72%;
				@include flexRS;
				color: #A0A0AD;
			}

			.select_location {
				height: 160rpx;
				margin: 20rpx 0;
				background: url(https://tyj-apk-1258993110.cos.ap-nanjing.myqcloud.com/new_app/map.png) no-repeat center;
				background-size: 100%;
				@include flexRC;

				.but {
					color: #fff;
					padding: 8rpx 36rpx;
					background-color: #FB652E;
					border-radius: 4rpx;
					@include dWeight;
				}
			}

			.store_status {
				width: 72%;
				@include flexR;
				flex-wrap: wrap;

				.status_item {
					@include flexR;
					white-space: nowrap;
					margin-right: 32rpx;
					margin-bottom: 24rpx;

					text {
						@include dfont;
						margin-left: 12rpx;
					}
				}
			}
		}

		.buttons {
			@include flexC;
			width: calc(100% - 64rpx);
			margin: 0 auto;
			padding: 40rpx 0;

			.agreement {
				@include flexR;
				@include dfont(26rpx);
				color: #A0A0AD;
				margin-bottom: 44rpx;
			}
		}

		.lines {
			width: 100%;
			height: 16rpx;
			background: $backColor;
		}

		.store_state {
			width: calc(100% - 64rpx);
			margin: 20rpx auto;
			background: $background-color;
			border-radius: 16rpx;
			@include flexR;
			padding: 32rpx 0;

			.state_left {
				margin-left: 32rpx;
				border-radius: 48rpx;
				width: 12%;

				image {
					width: 48rpx;
					height: 48rpx;
				}
			}

			.state_right {
				@include flexC;
				@include dfont(24rpx);
				color: #A0A0AD;

				.status {
					@include titlefont(32rpx);
				}

				.entryRemark {
					margin-top: 8rpx;
				}
			}
		}

		.imagelist {
			width: 100%;
			@include flexR;
			flex-wrap: wrap;
		}
	}
</style>